#!/bin/sh

#
# This script is used to get the main class of a JAR file,
# ie The class launched by default (cf MANIFEST.MF)
#

#
# Arguments : 1 - JAR file path
#
# STDOUT = the main class (eg : "foo.Bar")
#          or an error description (in this case retcode is not 0)
#
#
# RETCODE :
#     0   no errors
#     1   arguments refused ($1 is not an existing file or does not exists)
#     2   MANIFEST not found
#     3   Main class not found
#     4   Can't find "unzip" nor "jar" tool
#

#
# Dependences :   "jar" or "unzip" command
#
#

# init vars
JARFILE=$1
FILE_EXTRACTED=META-INF/MANIFEST.MF

ERR_ARG=$((1))
ERR_MANIFEST=$((2))
ERR_MAINCLASS=$((3))
ERR_NO_EXTRACTOR=$((4))


#
# In : arg1 : a command name (such as "unzip")
# Out : 0 if this command exists, non-zero otherwise.
exist_cmd() {
CMD_NAME="$1"

which ${CMD_NAME} > /dev/null 2>&1

return $?
}


if ! test -f "${JARFILE}"
then
echo -e "USAGE : $0 <jarfilename>\n\t Trying $0 $*"
exit ${ERR_ARG}
fi


if ! ( exist_cmd jar || exist_cmd unzip )
then
echo "Can't find \"jar\" nor \"unzip\" extraction tool."
exit ${ERR_NO_EXTRACTOR}
fi


# get extractor tool
if exist_cmd jar
then
EXTRACTOR="jar xf"
else
# echo yes to overwite if asked
EXTRACTOR="echo y | unzip"
fi

# extraction
eval ${EXTRACTOR} "${JARFILE}" "${FILE_EXTRACTED}"  > /dev/null 2>&1


# Search Manifest file
if ! test -f "${FILE_EXTRACTED}"
then
echo "ERROR : MANIFEST.MF not found"
exit ${ERR_MANIFEST}
fi

# get main class name
CLASS_NAME=$(grep -i '^main-class *:' "${FILE_EXTRACTED}"| cut -d ':' -f 2)
CLASS_NAME=$(echo ${CLASS_NAME} | sed 's/  *//g')

if test "${CLASS_NAME}" = ""
then
echo "ERROR : Main class not found"
exit ${ERR_MAINCLASS}
fi

# print main class name
echo ${CLASS_NAME}


rm -f ${FILE_EXTRACTED} > /dev/null 2>&1
rmdir META-INF > /dev/null 2>&1
